﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace DroidClaim.BL
{
    /// <summary>
    /// Summary description for UploadFile
    /// </summary>
    public class UploadFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            FileResultDto dto = this.SaveFile(context);

            context.Response.ContentType = "application/json";
            context.Response.Write(new JavaScriptSerializer().Serialize(dto));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private FileResultDto SaveFile(HttpContext context)
        {
            FileResultDto fileResultDto = new FileResultDto();
            fileResultDto.Result = false;
            if (context.Request.Files != null && context.Request.Files.Count > 0)
            {
                var file = context.Request.Files;
                string path = context.Server.MapPath("~/images/Temp");
                if (!Directory.Exists(path))
                {
                    DirectoryInfo di = Directory.CreateDirectory(path);
                }

                fileResultDto.ListFiles = new List<string>();
                for (int i = 0; i < file.Count; i++)
                {
                    HttpPostedFile myFile = file[i];
                    fileResultDto.ErrorMsg += "" + myFile.ContentLength;
                    if (myFile.ContentLength != 0)
                    {
                        string ext = myFile.FileName.Substring(myFile.FileName.LastIndexOf(".") + 1);
                        string filename = Guid.NewGuid() + "." + ext;
                        myFile.SaveAs(Path.Combine(path, filename));
                        fileResultDto.ListFiles.Add("images/Temp/" + filename);
                    }
                }
                fileResultDto.Result = true;
                fileResultDto.ErrorMsg += "" + context.Request.Files.Count;
            }

            return fileResultDto;
        }


        public class FileResultDto
        {
            public bool Result { get; set; }
            public string ErrorMsg { get; set; }
            public List<string> ListFiles { get; set; }
        }
    }
}